package cn.pengpeng.day03.friends;

import java.io.IOException;
import java.util.Arrays;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class FriendsStepTwo {

	public static class FriendsStepTwoMapper extends Mapper<LongWritable, Text, Text, Text> {

		@Override
		protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, Text>.Context context)
				throws IOException, InterruptedException {
			// A	I,K,C,B,G,F,H,O,D,
			String[] split = value.toString().split("\t");
			String friend = split[0];
			
			String[] persons = split[1].split(",");
			Arrays.sort(persons);
			
			for(int i=0;i<persons.length-1;i++) {
				for(int j=i+1;j<persons.length;j++) {
					// 输出 用户对作为key，他俩的共同好友作为value
					context.write(new Text(persons[i]+"-"+persons[j]), new Text(friend));
				}
				
			}
			
			
		}

	}

	public static class FriendsStepTwoReducer extends Reducer<Text, Text, Text, Text> {

		@Override
		protected void reduce(Text pair, Iterable<Text> friends, Reducer<Text, Text, Text, Text>.Context context)
				throws IOException, InterruptedException {
			
			StringBuilder sb = new StringBuilder();
			for (Text f : friends) {
				sb.append(f.toString()).append(" ");
			}

			context.write(pair,new Text(sb.toString()));
		}

	}

	public static void main(String[] args) throws Exception {
		Configuration conf = new Configuration();
		Job job = Job.getInstance(conf);

		job.setJarByClass(FriendsStepTwo.class);

		job.setMapperClass(FriendsStepTwoMapper.class);
		job.setReducerClass(FriendsStepTwoReducer.class);

		job.setMapOutputKeyClass(Text.class);
		job.setMapOutputValueClass(Text.class);

		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(Text.class);

		FileInputFormat.setInputPaths(job, new Path("F:\\mrdata\\friends\\out1"));
		FileOutputFormat.setOutputPath(job, new Path("F:\\mrdata\\friends\\out2"));

		job.setNumReduceTasks(1);

		boolean res = job.waitForCompletion(true);
		System.exit(res ? 0 : 1);
	}

}
